import { useState, useEffect, useRef } from 'react';
import './Top.css';
import { Link } from 'react-router-dom';
import { accountService } from '../../../service/accountService';
import { productService } from '../../../service/productService';
import { common_utils } from '../../../utils/utils';

export function Top() {

   
    return (
        <>
            <div className="header">
                 <div className="store_icon" onClick={() => common_utils.toMain()}></div>
                <Account />
                <Search />
                
            </div>
            <QuickLink />

        </>
    );
}
function Account() {



    let User = UserInfo();
    
    let cartRouter="/user/"+common_utils.getUsername()+"/cart";

    return (
        <div className="account">
            <Link to={cartRouter}><div className="cart"></div></Link>
            <div className="divider"></div>
            {User}
            <div className="divider"></div>
            
           </div>
    );
}
function UserInfo() {
    const [user, setUser] = useState(null);
    useEffect(() => {
        const storedUser = localStorage.getItem("user");
        console.log("storedUser:", storedUser);
        if (storedUser) {
            setUser(JSON.parse(storedUser));
        }
    }, []);

    const handleSignOut = () => {

        setUser(null); // 清空 user 状态
        accountService.logout(); // 调用注销服务
    };

    let User = null;
    if (user == null) {
        User = <Link to="/login"><span>Sign In</span></Link>;
    } else {
       var router="/user/"+user.username+"/info";
        User = (
            <>
                <span onClick={handleSignOut} style={{ cursor: "pointer" }}>Sign Out</span>
                <div className="divider"></div>
                <Link to={router}>
                    <img src={common_utils.getServerImageURL(user.image)} alt="User Avatar" />
                </Link>
                
                <Link style={{ textDecoration: 'none',color: 'orange' }} to={`/user/${common_utils.getUsername()}/package`}>My Packages</Link>
            
        
            </>
        );
    }

    return User;
}
function Search() {

    const [searchTerm, setSearchTerm] = useState("");
  const [suggestions, setSuggestions] = useState([]);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const searchRef = useRef(null);

  // 处理搜索输入变化
  const handleSearchChange = (e) => {
    const value = e.target.value;
    setSearchTerm(value);

    if (value.trim() === "") {
      setSuggestions([]);
      setShowSuggestions(false);
      return;
    }

    // 调用后端接口获取搜索结果
    
    
    productService.getSearchProduct(value, function (response) {
      setSuggestions(response.data || []); // 将后端返回的数据设置为建议列表
      setShowSuggestions(true);
    });
  };

  // 处理建议项点击
  const handleSuggestionClick = (suggestion) => {
    setSearchTerm(suggestion.name);
    setShowSuggestions(false);
    common_utils.jumpTo("/products/" + suggestion.productid+"/items"); // 跳转到搜索结果页面
  };

  // 处理搜索提交
  const handleSearchSubmit = (e) => {
    e.preventDefault();
    setShowSuggestions(false);
    common_utils.jumpTo("/products/" + getProductIdByName(suggestions,searchTerm)+"/items"); // 跳转到搜索结果页面
  };
  const getProductIdByName = (products, name) => { 

    if(products.length === 0) return null;

    for(let i = 0; i < products.length; i++) {
      if (products[i].name.toLowerCase() === name.toLowerCase()) {
        return products[i].productid;
      }
    }

    return null; // 如果没有找到匹配的产品，返回 null
}



  // 点击外部关闭建议列表
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (searchRef.current && !searchRef.current.contains(event.target)) {
        setShowSuggestions(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);



    return (
        
    <div className="search" ref={searchRef} style={{ position: 'relative' }}>
       <form onSubmit={handleSearchSubmit}>
           <input
            type="text"
            placeholder="Search pets..."
            value={searchTerm}
            onChange={handleSearchChange}
          />
          <button type="submit">Search</button>
          
          {showSuggestions && suggestions.length > 0 && (
            <div className="suggestions-container" style={{
              position: 'absolute',
              backgroundColor: 'white',
              border: '1px solid #ccc',
              width: '220px',
              zIndex: 1000,
              right: '130px',
              top: '35px',
              padding: '5px',
              boxShadow: '0 2px 5px rgba(0,0,0,0.2)',
              maxHeight: '300px',
              overflowY: 'auto'
            }}>
              <ul style={{ listStyle: 'disc inside', padding: '0 0 0 10px', margin: 0 }}>
                {suggestions.map((suggestion,index) => (
                 <li 
                 key={index} 
                 onClick={() => handleSuggestionClick(suggestion)}
                 style={{ 
                   cursor: 'pointer', 
                   padding: '5px 0',
                   fontSize: '14px'
                 }}
               >
                {suggestion.name}
               </li> 
                ))}
              </ul>
            </div>
          )}
        </form>
    </div>
    
    );
}
function QuickLink() {
    return (
        <ul className="categories">
            <li><Link to="/categories/BIRDS/products"><img src={require('../../../images/sm_birds.gif')} alt="Category 1" /></Link></li>
            <li className="divider"></li>
            <li><Link to="/categories/CATS/products"><img src={require('../../../images/sm_cats.gif')} alt="Category 2" /></Link></li>
            <li className="divider"></li>
            <li><Link to="/categories/DOGS/products"><img src={require('../../../images/sm_dogs.gif')} alt="Category 3" /></Link></li>
            <li className="divider"></li>
            <li><Link to="/categories/FISH/products"><img src={require('../../../images/sm_fish.gif')} alt="Category 4" /></Link></li>
            <li className="divider"></li>
            <li><Link to="/categories/REPTILES/products"><img src={require('../../../images/sm_reptiles.gif')} alt="Category 5" /></Link></li>
        </ul>
    )
}
